package com.xysq.widget;

import android.util.Log;
import android.widget.AbsListView;
import android.widget.AdapterView;

/**
 * Created by Steward_Han on 2015/9/14.
 */
public class ScrollListener implements AbsListView.OnScrollListener{
    private AdapterView dataList;
    private int number = 20;
    private int currentPage = 1;
    private int maxPage = 50;
    private boolean loadFinish = true;
    private LoadData loadData;
    private int headListSize;

    public ScrollListener(AdapterView dataList, int number, int maxPage, boolean loadFinish, LoadData loadData){
        this.dataList = dataList;
        this.number = number;
        this.maxPage = maxPage;
        this.loadFinish =
                loadFinish;
        this.loadData = loadData;
    }

    public ScrollListener(AdapterView dataList, boolean loadFinish, LoadData loadData){
        this.dataList = dataList;
        this.loadFinish = loadFinish;
        this.loadData = loadData;
    }
    public ScrollListener(AdapterView dataList, boolean loadFinish, int headListSize, LoadData loadData){
        this.dataList = dataList;
        this.loadFinish = loadFinish;
        this.loadData = loadData;
        this.headListSize = headListSize;
    }

    public void setLoadFinish(boolean loadFinish){
        this.loadFinish = loadFinish;
    }

    public void setCurrentPage(int currentPage){
        this.currentPage = currentPage;
    }

    public boolean getLoadFinish(){
        return loadFinish;
    }

    public int getCurrentPage(){
        return currentPage;
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        final int loadtotal = totalItemCount;
        int lastItemId = dataList.getLastVisiblePosition(); // 获取当前屏幕最后Item的ID
        if ((lastItemId + 1) == totalItemCount) { // 达到数据的最后一条记录
            if (totalItemCount > 0) {
                // 当前页
                totalItemCount = totalItemCount - headListSize;
                int currentpage = totalItemCount % number
                        == 0 ? totalItemCount / number : totalItemCount / number + 1;
                int nextPage = currentpage + 1; // 下一页
                this.currentPage = nextPage;
                if (currentpage == 1 && lastItemId + 1 < number) {

                } else if (nextPage <= maxPage && loadFinish) {
                    loadFinish = false;
                    loadData.loadMyData();
                }
            }
        }
    }
}
